package com.erp.filter;

import com.erp.conf.Constant;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录过滤器，鉴权
 *
 * @Author lqa
 * @Date 2022-05-18 14:12:19
 */
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 加工
        // 1.加工一下请求对象和响应对象
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 2.获取session
        HttpSession session = request.getSession();
        // 3.获取登录标识符
        boolean isLogin = session.getAttribute("isLogin") != null && (boolean) session.getAttribute("isLogin");
        // 4.判断一下是否是登录请求和登录页面，
        //   始终放行这两个请求
        String url = request.getRequestURI();
        // 登录过的用户不再访问登录页面
        if (url.endsWith("login.jsp") && isLogin) {
            response.sendRedirect(request.getContextPath() + "/index.jsp");

        }
        // 不需要鉴权的请求
        else if (isContainsUrl(url)) {
            filterChain.doFilter(request, response);

        } else {
            if (isLogin) {
                // 放行请求。
                // 注意点：不管我们过滤器的doFilter方式执行什么操作
                // 最后都需要放行请求或者重定向或者请求转发到别的页面

                // 登录有效期校验
                if (userExpireTime((long) session.getAttribute("time"))) {
                    // 1.把isLogin 设置为false
                    session.setAttribute("isLogin",false);
                    response.sendRedirect(request.getContextPath() + "/logout.jsp");
                } else {
                    filterChain.doFilter(request, response);
                }
            } else {
                // 未登录跳转登录页面
                response.sendRedirect(request.getContextPath() + "/login.jsp");
            }
        }


    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }

    // url是否存在
    private boolean isContainsUrl(String url) {
        boolean isExist = false;
        for (String item : Constant.notAuthResource) {
            if (url.contains(item)) {
                isExist = true;
            }
        }
        return isExist;
    }

    // 判断用户是否超出登录时间
    private boolean userExpireTime(Long loginTime) {
        Long now = System.currentTimeMillis(); // 时间戳是毫秒数
        return ((now - loginTime) / 1000) > Constant.loginExpire;

    }
}